//var basePath = "http://123.206.33.201/gp/";
//var basePath = "http://127.0.0.1/GraduationProject";
var flag ;// 新增修改地址标识
var orderList = []; // 准备提交的商品数据

$(function(){
	
	getAllAddress();
	loadOrderList();
	fullArea();
	
	// 设置是否默认
	$("#ifDefault").on("click",function(){
		$("#checkIpt").toggle();
		$("#checkedIpt").toggle();
	});

	// 重新新建地址
	$("#newAddress").on("click",function(){
		flag = true;
		$("#addAddressTableForm").show();
		$("#addAddress").show();
		$(this).show();
		$("#reciveAddress").hide();
		$("#addressChage").hide();
	});
	
	// 取消新增
	$("#cancelBtn").on("click",function(){
		$("#addressForm")[0].reset();
		$("#addAddressTableForm").hide();
		$("#addAddress").hide();
		$("#reciveAddress").show();
		$("#addressChage").show();
	});
	
	// 修改地址
	$("#modifyAddressBtn").on("click",function(){
		flag = false;
		modifyAddress();
	});
	
	
	// 地址保存
	$("#saveBtn").on("click",function(){
		saveAddress();
	});
	
});

/**
 * 加载数据
 */
var orderCode = sessionStorage.getItem("orderCode");
function loadOrderList(){
	$.ajax({
		type:"get",
		url:basePath + "/order/noSubmitOrder/" + orderCode,
		async:false,
		success:function(data){
			if(data.status == "200"){
				orderList = data.obj;
				console.log(data);
				var $tbody = $("#orderListTable tbody");
				$tbody.html("");
				var total = 0;
				var transportFee = 0;
				for(var i in data.obj){
					var $tr = $("<tr><td><img src='"+data.obj[i].images.split(",")[0]+"' alt='' /><span>"+data.obj[i].goodsName+"</span></td>" +
							"<td><span>￥" + data.obj[i].price + "</span></td><td><span>" + data.obj[i].quantity + "</span></td>" +
							"<td><span>￥" + data.obj[i].total + "</span></td><td><span>￥" +  data.obj[i].total + "</span></td></tr>");
					
					$tbody.append($tr);
					total +=  parseInt(data.obj[i].total);
				}
				console.log(total);
				$("#plusPrice").html(total);
				$("#diliverPrice").html();
				$("#total").html(parseInt($("#diliverPrice").html()) + total);
			}
		}
	});
}

/**
 * 提交订单
 */
function commitOrder(){
	
	var params = {};
//	params.orderCode = orderCode;
	params.orderId = orderCode;//订单编号
	params.receiverName = $("#reciveAddress li span.reName").html();//收货人
	params.receiverAddress = $("#reciveAddress li span.reAddress").html();//收货地址
	params.receiverPhone = $("#reciveAddress li span.reTel").html();//电话
	params.couponCode ="" ;//优惠券
	params.plusPrice = $("#plusPrice").html();//商品总价
	params.specialOffer =0 ;//运费
	//params.totalPrice = $("#total").html();
	params.amount = $("#total").html();//最后支付金额
	params.payType = "22"; // 支付方式默认平台币支付
	params.transportType = "6";
	
	sessionStorage.setItem("orderCode",orderCode);
	sessionStorage.setItem("total", $("#total").html());

	// 模态框2显示
	$("#myModal2").modal("show");
	// 点击确认密码
	$("#surePay").on("click",function (){
		var password= $("#inputPwd").val();
		console.log(password);
		$.ajax({
			type:"post",
			url:basePath + "/order/passwordConfirm",
			data:{"password":password},
			async:true,
			success:function(data){
				// 确认密码后进行支付
				if(data.status == "200"){
					$.ajax({
						type:"post",
						url:basePath + "/order/pay",
						data:JSON.stringify(params),
						async:false,
						dataType : 'json',
				        contentType : 'application/json',
						success:function(data){
							if(data.status == "200"){
								// 付款成功后跳转
								$("#myModal3").modal("show");
								$("#myModal2").modal("hide");
								$("#sureHref").on("click",function (){
									window.location.href = "indexPage.html";
								});
							}
						}
					});
				}else{
					$("#returnMsg").show();
				}
			}
		});
	});	
	
}

/**
 * 获取当前登录用户的所有收货地址
 */
function getAllAddress(){
	var addressList = [];
	$.ajax({
		type:"get",
		url:basePath + "/address/list",
		async:false,
		success:function(data){
			if(data){
				addressList = data.obj;
				// 页面显示地址
				if(data.obj == null || data.obj == ""){
					flag = true;
					$("#addAddressTableForm").show();
					$("#addAddress").show();
					$("#cancelBtn").hide();
					$("#reciveAddress").hide();
					$("#addressChage").hide();
				}else{
					// 隐藏新增框
					$("#addAddressTableForm").hide();
					$("#addAddress").hide();
					
					for (var i in data.obj) {
						if(data.obj[i].isDefault == 1){
							// 有默认地址时填充默认地址的信息
							$("#reciveAddress li span.addressId").html(data.obj[i].addressId);
							$("#reciveAddress li span.reName").html(data.obj[i].userName);
							$("#reciveAddress li span.reTel").html(data.obj[i].tel);
							$("#reciveAddress li span.reAddress").html(data.obj[i].streetName);
							break;
						}else{
							// 没有默认地址时默认填充第一条地址
							$("#reciveAddress li span.addressId").html(data.obj[0].addressId);
							$("#reciveAddress li span.reName").html(data.obj[0].userName);
							$("#reciveAddress li span.reTel").html(data.obj[0].tel);
							$("#reciveAddress li span.reAddress").html(data.obj[0].streetName);
						}
					}
					
					// 显示地址信息
					$("#reciveAddress").show();
					$("#addressChage").show();
				}
			}
		}
	});

	return addressList;
}

/**
 * 修改地址
 */
function modifyAddress(addressId){
	addressId = $("#reciveAddress li span.addressId").html();
	
	$.ajax({
		type:"get",
		url:basePath + "/address/detail/"+addressId,
		async:true,
		success:function(data){
			if(data.status == "200"){
				var area = data.obj.streetName.split(",");
				$("#cityName").val(area[0]);
				$("#areaName").val(area[1]);
				$("#subAreaName").val(area[2]);
				$("#streetNameTextArea").val(area[3]);
				
				var input = $("#addAddressTable input");
				for(var i in input){
					for(var j in data.obj){
						if(input.eq(i).attr("name") == j){
							input.eq(i).val(data.obj[j]);
						}
					}
				}

				// 是否默认
				if(data.obj.isDefault == 1){
					$("#checkIpt").css("display","none");
					$("#checkedIpt").css("display","block");
				}else{
					$("#checkIpt").css("display","block");
					$("#checkedIpt").css("display","none");
				}
				
				
				$("#addAddressTableForm").show();
				$("#addAddress").show();
				$("#reciveAddress").hide();
				$("#addressChage").hide();
			}
		}
	});
}

/**
 * 新增地址
 */
function saveAddress(){
	var adeData = $("#addressForm").serializeObject();
	if($("#checkIpt").css("display") == "none"){
		adeData.isDefault = 1;
	}else{
		adeData.isDefault = 0;
	}
	adeData.streetName = $("#cityName").val() + "," + $("#areaName").val() + "," + $("#subAreaName").val() + "," + adeData.streetName ;
	
	if(flag){
		var url = basePath + "/address/add";
	}else{
		var url = basePath + "/address/edit";
	}
	$.ajax({
		type:"post",
		url:url,
		data:adeData,
		async:true,
		success:function(data){
			if(data){
				if(data.status == "200"){
					$("#reciveAddress li span.addressId").html(adeData.addressId);
					$("#reciveAddress li span.reName").html(adeData.userName);
					$("#reciveAddress li span.reTel").html(adeData.tel);
					$("#reciveAddress li span.reAddress").html(adeData.streetName);

					$("#addressForm")[0].reset();
					$("#addAddressTableForm").hide();
					$("#addAddress").hide();
					$("#reciveAddress").show();
					$("#addressChage").show();
				}
			}
		}
	});
}

/**
 * 更换收货地址
 * @returns
 */
function changeAddress(){
	$("#myModal").modal("show");
	var modalBody = $("#myModal .modal-body");
	modalBody.html("");
	
	$.ajax({
		type:"get",
		url:basePath + "/address/list",
		async:false,
		success:function(data){
			if(data){
				var allAddress =  data.obj;
				for(var i in allAddress){
					var ul = $("<ul class='"+(allAddress[i].isDefault ?'onChose':'')+"' onclick='change(this)' data-id='"+allAddress[i].addressId+"'><li><span>收&nbsp;&nbsp;货&nbsp;&nbsp;人:</span>&nbsp;&nbsp;<span class='text userNameC' >"+allAddress[i].userName+"</span></li>" +
							"<li><span>联系方式：</span><span class='text telC'>"+allAddress[i].tel+"</span></li>" +
							"<li><span>收货地址：</span><span class='text streetNameC'>"+allAddress[i].streetName+"</span><span class='fl-r default' data-default='"+allAddress[i].isDefault+"' style='display:"+(allAddress[i].isDefault ?'inline-block':'none')+"'>默认地址</span></li></ul>");
					modalBody.append(ul);
				}
			}
		}
	});
}

/**
 * 选择
 * @param obj
 * @returns
 */
function change(obj){
	$(obj).addClass("onChose").siblings().removeClass("onChose");
}

/**
 * 确定选择
 * @returns
 */
function sureChose(){
	var data = {};
	data.addressId = $("#myModal .modal-body ul.onChose").attr("data-id");
	data.userName = $("#myModal .modal-body ul.onChose span.userNameC").html();
	data.tel = $("#myModal .modal-body ul.onChose span.telC").html();
	data.streetName = $("#myModal .modal-body ul.onChose span.streetNameC").html();
	data.default = $("#myModal .modal-body ul.onChose span.default").attr("data-default");

	$("#reciveAddress li span.addressId").html(data.addressId);
	$("#reciveAddress li span.reName").html(data.userName );
	$("#reciveAddress li span.reTel").html(data.tel);
	$("#reciveAddress li span.reAddress").html(data.streetName);

	if(data.default == 1){
		$("#checkIpt").css("display","none");
		$("#checkedIpt").css("display","block");
	}else{
		$("#checkIpt").css("display","block");
		$("#checkedIpt").css("display","none");
	}
	
}

/**
 * 获取当前用户信息
 */
function getUserInfo(){
	var currentUser;
	$.ajax({
		type:"get",
		url:basePath + "/user/detail",
		async:false,
		success:function(data){
			if(data){
				currentUser = data.obj;
			}
		}
	});
	return currentUser;
}

/**
 * 地址加载
 */
function getArea(level){
	var datalist = [];
	$.ajax({
		type:"get",
		url:basePath + "/address/area/" + level,
		async:false,
		success:function(data){
			if(data){
				datalist = data.obj;
			}
			
		}
	});
	return datalist;
}

/**
 * 一级地址数据填充
 */
function fullArea(){
	var cityData = getArea(1);
	var $city = $("#cityName");
	$city.html("");
	 $("#areaName").html("");
	 $("#subAreaName").html("");
	var allOption = $("<option value=''  data-id=''>全部</option>");
	$city.append(allOption);
	
	for(var i in cityData){
		var $option = $("<option value='"+cityData[i].name+"'  data-id='"+cityData[i].id+"'>"+cityData[i].name+"</option>");
		 $city.append($option);
	}
}

/**
 * 二级地址填充
 */
function areaData(obj){
	var pid = $(obj).find("option:selected").attr("data-id");
	var areaData = getArea(pid);
	var $area = $("#areaName");
	$area.html("");
	$("#subAreaName").html("");
	var allOption = $("<option value=''  data-id=''>全部</option>");
	$area.append(allOption);
	
	for(var i in areaData){
		var $option = $("<option value='"+areaData[i].name+"'  data-id='"+areaData[i].id+"'>"+areaData[i].name+"</option>");
		$area.append($option);
	}
}

/**
 * 三级地址填充
 */
function subareaData(obj){
	var pid = $(obj).find("option:selected").attr("data-id");
	var subareaData = getArea(pid);
	var $subarea = $("#subAreaName");
	$subarea.html("");
	var allOption = $("<option value=''  data-id=''>全部</option>");
	$subarea.append(allOption);
	
	for(var i in subareaData){
		var $option = $("<option value='"+subareaData[i].name+"'  data-id='"+subareaData[i].id+"'>"+subareaData[i].name+"</option>");
		$subarea.append($option);
	}
}




